package com.sinodata.bsm.cicp.finder.weblogic9;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.Query;
import javax.management.QueryExp;
import javax.management.remote.JMXConnector;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.finder.Finder;
import com.sinodata.bsm.cicp.util.JmxUtil;

public class WebApplicationFinder extends Finder {

    private static final Logger logger = Logger.getLogger(WebApplicationFinder.class);

    /*@Override
    public List find(ResValue resValue, ResAttributeValValue[] attrVals, ResAttributeValue[] attributes) {
        List resources = new ArrayList();
        String ip = host;
        String port = attrVals[1].getAttrValue();
        ObjectName service;
        String name = null;
        JMXConnector connector = null;
        MBeanServerConnection connection = null;
        try {
            connector = JmxUtil.getConnection(JmxUtil.WEBLOGIC, ip + ":" + port);
            connection = connector.getMBeanServerConnection();
            service = new ObjectName("com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean");
            Object domainConfiguration = connection.getAttribute(service, "DomainConfiguration");
            ObjectName[] appDeployments = (ObjectName[]) connection.getAttribute((ObjectName) domainConfiguration, "AppDeployments");
            QueryExp typefilter = Query.match(Query.attr("Type"), Query.value("ApplicationRuntime"));
            QueryExp appfilter = null;
            if ((appDeployments != null) && (appDeployments.length > 0)) {
                for (ObjectName objectName : appDeployments) {
                    name = objectName.getKeyProperty("Name");
                    QueryExp tfilter = Query.match(Query.attr("ApplicationName"), Query.value(name));
                    if (appfilter == null) {
                        appfilter = tfilter;
                    } else {
                        appfilter = Query.or(appfilter, tfilter);
                    }
                }
                QueryExp destfilter = Query.and(typefilter, appfilter);
                Set test = connection.queryNames(new ObjectName("com.bea:*"), destfilter);
                Iterator it = test.iterator();
                String applicationName = null;
                String contextRoot = null;
                while (it.hasNext()) {
                    ObjectName objName = (ObjectName) it.next();
                    applicationName = objName.getKeyProperty("Name");
                    ObjectName[] componentRuntimes = (ObjectName[]) connection.getAttribute(objName, "ComponentRuntimes");
                    String attributeNames[] = new String[] { "ContextRoot" };
                    for (ObjectName objectName2 : componentRuntimes) {
                        Object attrValues[] = null;
                        attrValues = JmxUtil.getAttribute(connection, objectName2, attributeNames);
                        contextRoot = attrValues[0].toString();
                    }
                }
                List oneResource = CreateOneResource(applicationName, contextRoot, attributes);
                resources.add(oneResource);
            }
        } catch (Exception e) {
            logger.error("failed to find weblogic9 WebApplication", e);
            resources = null;
        } finally {
            JmxUtil.closeConnector(connector);
        }
        return resources;
    }*/

    /*private List CreateOneResource(String applicationName, String contextRoot, ResAttributeValue[] attributes) {
        List aRes = new ArrayList();
        ResValue res = new ResValue();
        ResAttributeValValue valValue = null;
        res.setIp(host); // host IP address
        res.setInternalId(host + "weblogic9" + applicationName); // Internal ID for agent
        res.setName("WebApplication." + applicationName);
        aRes.add(res);
        valValue = com.union.pub.util.CollectorUtil.getResAttrValValue(attributes[0].getId(), applicationName);
        aRes.add(valValue);
        valValue = com.union.pub.util.CollectorUtil.getResAttrValValue(attributes[1].getId(), contextRoot);
        aRes.add(valValue);
        return aRes;
    }*/

    @SuppressWarnings("unchecked")
    @Override
    public List<String[]> find(String ip, Map params) {
        List<String[]> list = new ArrayList<String[]>();
        String port = (String) params.get("PORT");
        ObjectName service;
        String name = null;
        JMXConnector connector = null;
        MBeanServerConnection connection = null;
        try {
            connector = JmxUtil.getConnection(ip, Integer.parseInt(port));
            connection = connector.getMBeanServerConnection();
            service = new ObjectName("com.bea:Name=DomainRuntimeService,Type=weblogic.management.mbeanservers.domainruntime.DomainRuntimeServiceMBean");
            Object domainConfiguration = connection.getAttribute(service, "DomainConfiguration");
            ObjectName[] appDeployments = (ObjectName[]) connection.getAttribute((ObjectName) domainConfiguration, "AppDeployments");
            QueryExp typefilter = Query.match(Query.attr("Type"), Query.value("ApplicationRuntime"));
            QueryExp appfilter = null;
            if ((appDeployments != null) && (appDeployments.length > 0)) {
                for (ObjectName objectName : appDeployments) {
                    name = objectName.getKeyProperty("Name");
                    QueryExp tfilter = Query.match(Query.attr("ApplicationName"), Query.value(name));
                    if (appfilter == null) {
                        appfilter = tfilter;
                    } else {
                        appfilter = Query.or(appfilter, tfilter);
                    }
                }
                QueryExp destfilter = Query.and(typefilter, appfilter);
                Set test = connection.queryNames(new ObjectName("com.bea:*"), destfilter);
                Iterator it = test.iterator();
                String applicationName = null;
                String contextRoot = null;
                while (it.hasNext()) {
                    ObjectName objName = (ObjectName) it.next();
                    applicationName = objName.getKeyProperty("Name");
                    ObjectName[] componentRuntimes = (ObjectName[]) connection.getAttribute(objName, "ComponentRuntimes");
                    String attributeNames[] = new String[] { "ContextRoot" };
                    for (ObjectName objectName2 : componentRuntimes) {
                        Object attrValues[] = null;
                        attrValues = JmxUtil.getAttribute(connection, objectName2, attributeNames);
                        contextRoot = attrValues[0].toString();
                    }
                }
                String[] info = new String[5];
                list.add(info);
                info[0] = ip + "weblogic9" + applicationName;
                info[1] = "WebApplication." + applicationName;
                info[2] = "WebApplication " + applicationName;
                info[3] = applicationName;
                info[4] = contextRoot;
            }
            return list;
        } catch (Exception e) {
            logger.error("failed to find weblogic9 WebApplication", e);
            return null;
        } finally {
            JmxUtil.closeConnector(connector);
        }
    }
}
